package com.openwater.core;

import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLES20;

import com.openwater.tools.BufferAllocator;
import com.openwater.tools.math.MatrixState;

/**
 * 
 * @author fupeng
 * @description x-y panel
 */
public class Quad {

    private float mWidth = 1.0f;
    private float mHeight = 1.0f;

    private int mProgram;
    private int muMVPMatrixHandle;
    private int maPositionHandle;
    private int maTexCoorHandle;

    private FloatBuffer mVertexBuffer = null;
    private FloatBuffer mTextureBuffer = null;

    public Quad(int program, float width, float height) {
        mWidth = width;
        mHeight = height;
        mProgram = program;
        initVertex();
        initShader();
    }

    private void initShader() {
        maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
        maTexCoorHandle = GLES20.glGetAttribLocation(mProgram, "aTexCoor");
        muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
    }

    private void initVertex() {
        final float w = mWidth / 2.0f;
        final float h = mHeight / 2.0f;
        final float vertices[] = { w, h, -w, h, -w, -h, w, -h};
        final float texCoords[] = { 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f };
        mVertexBuffer = BufferAllocator.toFloatBuffer(vertices);
        mTextureBuffer = BufferAllocator.toFloatBuffer(texCoords);
    }

    public void drawSelf(int texid) {
        MatrixState.pushMatrix();
        GLES20.glUseProgram(mProgram);
        GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
        GLES20.glVertexAttribPointer(maPositionHandle, 2, GLES20.GL_FLOAT, false, 2 * 4, mVertexBuffer);
        GLES20.glVertexAttribPointer(maTexCoorHandle, 2, GLES20.GL_FLOAT, false, 2 * 4, mTextureBuffer);
        GLES20.glEnableVertexAttribArray(maPositionHandle);
        GLES20.glEnableVertexAttribArray(maTexCoorHandle);
        GLES20.glEnable(GL10.GL_TEXTURE_2D);
        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texid);
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, 4);
        MatrixState.popMatrix();
    }
}
